package com.prodog.message.sender;

import love.forte.simbot.Bot;
import love.forte.simbot.BotManager;
import love.forte.simbot.OriginBotManager;
import love.forte.simbot.definition.Friend;
import love.forte.simbot.definition.Group;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class SimBotMessageSender implements MessageSender {

    public Map<String, Group> getGroups() {
        Map<String, Group> groups = new HashMap<>();
        for (BotManager<?> manager : OriginBotManager.INSTANCE) {
            for (Bot bot : manager.all()) {
                bot.getGroups().forEach(group -> groups.put(group.getId().toString(), group));
            }
        }
        return groups;
    }

    public Map<String, Friend> getFriends() {
        Map<String, Friend> friends = new HashMap<>();
        for (BotManager<?> manager : OriginBotManager.INSTANCE) {
            for (Bot bot : manager.all()) {
                bot.getFriends().forEach(friend -> friends.put(friend.getId().toString(), friend));
            }
        }
        return friends;
    }

    @Override
    public void sendToGroup(String groupId, String msg) {
        Optional.ofNullable(getGroups().get(groupId)).ifPresent(group -> group.sendBlocking(msg));
    }

    @Override
    public void sendToSelf(String selfId, String msg) {
        Optional.ofNullable(getFriends().get(selfId)).ifPresent(friend -> friend.sendBlocking(msg));
    }

    @Override
    public void sendToGroups(String msg, Collection<String> groupIds) {
        groupIds.forEach(groupId -> sendToGroup(groupId, msg));
    }

    @Override
    public void sendToSelfs(String msg, Collection<String> selfIds) {
        selfIds.forEach(selfId -> sendToGroup(selfId, msg));
    }
}
